package com.xnfh.field.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.PolygonOptions
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.OnSelectListener
import com.lxj.xpopup.interfaces.SimpleCallback
import com.xnfh.common.bean.FieldDetailBean
import com.xnfh.common.bean.FieldJfJy
import com.xnfh.common.bean.FieldListBean
import com.xnfh.common.bean.FieldWeatherBean
import com.xnfh.common.bean.Record
import com.xnfh.common.constant.ArouterPath
import com.xnfh.common.utils.LocationEnclosureUtil
import com.xnfh.field.R
import com.xnfh.field.databinding.FragmentFieldLayoutBinding
import com.xnfh.common.pop.OpenAddressPop
import com.xnfh.field.ui.activity.FieldEditorActivity
import com.xnfh.field.ui.activity.FieldListActivity
import com.xnfh.field.ui.activity.FieldTendencyImageActivity
import com.xnfh.field.ui.activity.SoilMessageActivity
import com.xnfh.field.utils.FieldEnclosureMapUtil
import com.xnfh.field.viewmodel.FieldViewModel
import com.xnfh.framework.base.BaseFragment
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.framework.utils.JsonUtlis
import com.xnfh.image.ImageHelper

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/8 14:39
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/8 14:39
 * @UpdateRemark: 更新说明
 */
@Route(path = ArouterPath.FIELD.FIELD_FRAGMENT)
class FieldFragment : BaseFragment<FragmentFieldLayoutBinding>(),View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.fragment_field_layout

    private var aMap: AMap? = null
    private var currLocationMarker: Marker? = null
    private var curLatLng: LatLng? = null
    private var viewModel: FieldViewModel? = null
    private var areaId: String? = null
    private var fieldPolygon: Polygon? = null
    var maker: MarkerOptions? = null
    //当前地块的id
    private var currFieldId: String? = null
    private var centerCoordinate: String? = null
    private var detailBean: FieldDetailBean? = null

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBind.fieldName.setOnClickListener(this)
        mBind.fieldNoDataBut.setOnClickListener(this)
        mBind.fieldDetailTurangMessage.setOnClickListener(this)
        mBind.fieldDetailDkEdit.setOnClickListener(this)
        mBind.fieldDetailZsMessage.setOnClickListener(this)
        initMapView(savedInstanceState)
        //请求地块信息
        viewModel?.requestField()
    }

    override fun onClick(v: View?) {
        when(v){
            mBind.fieldName ->{
                FieldListActivity.start(requireActivity(), requestCode = FieldListActivity.REQUEST_CODE)
            }
            mBind.fieldNoDataBut ->{
                ARouter.getInstance().build(ArouterPath.HOME.ENCLOSURE_FIELD_ACTIVITY).navigation()
            }
            mBind.fieldDetailTurangMessage ->{
                val bundle = Bundle()
                bundle.putString("centerCoordinate",centerCoordinate)
                bundle.putString("fieldId",currFieldId)
                SoilMessageActivity.start(requireContext(),bundle)
            }
            mBind.fieldDetailZsMessage ->{
                val bundle = Bundle()
                if(detailBean == null){
                    TipsToast.showTips(R.string.adapter_no_data)
                    return
                }
                bundle.putSerializable("data",detailBean)
                FieldTendencyImageActivity.start(requireContext(),bundle)
            }
            mBind.fieldDetailDkEdit ->{
                XPopup.Builder(requireContext()).atView(mBind.fieldDetailDkEdit).asAttachList(
                    arrayOf(getString(R.string.str_edit),getString(R.string.str_lunzuo)),null,object :OnSelectListener{
                        override fun onSelect(position: Int, text: String?) {
                            if(detailBean == null) return
                            val bundle = Bundle()
                            bundle.putSerializable("data",detailBean!!)
                            if(position == 0){
                                bundle.putInt(FieldEditorActivity.INTENT_TAG,0)//编辑
                            }else{
                                bundle.putInt(FieldEditorActivity.INTENT_TAG,1)//轮作
                            }
                            FieldEditorActivity.start(requireActivity(),bundle,FieldEditorActivity.REQUEST_CODE)
                        }
                    }
                ).show()
            }
        }
    }


    override fun observe() {
        viewModel = FieldViewModel()

        /**
         * 请求地块列表，拿到第一个地块，请求地块详情接口
         */
        viewModel?.fieldData?.observe(this, object : BaseStateObserver<FieldListBean>(null) {
            override fun getRespDataSuccess(it: FieldListBean) {
                super.getRespDataSuccess(it)
                if (it.total > 0) {
                    mBind.fieldName.text = it.records[0].fieldName
                    currFieldId = it.records[0].fieldId
                    viewModel?.requestFieldDetail(it.records[0].fieldId)
                }
            }
        })

        /**
         * 获取地块详情，请求天气相关
         */
        viewModel?.fieldDetailData?.observe(this,
            object : BaseStateObserver<FieldDetailBean>(null) {
                override fun getRespDataSuccess(it: FieldDetailBean) {
                    super.getRespDataSuccess(it)
                    detailBean = it
                    centerCoordinate = it.centerCoordinate
                    //请求天气相关温度
                    viewModel?.requestFielsWeather(it.center02)
                    //获取积风、积雨
                    viewModel?.requestFiledJwJy(it.center02)
                    //设置地块详情信息 ----start----
                    ImageHelper.instance?.loadNetImg(
                        requireContext(), it.fileURL, mBind.fieldDetailPic,
                        com.xnfh.common.R.mipmap.image_error, com.xnfh.common.R.mipmap.image_error
                    )
                    //作物名称
                    it.plantCropName.let {
                        mBind.fieldDetailName.text =
                            "${resources.getString(R.string.field_zw_name_tips)}${it}"
                    }
                    //亩
                    it.areaMu.let {
                        mBind.fieldDetailMu.text =
                            "${it}${resources.getString(R.string.field_detail_mu)}"
                    }
                    //品种名称 暂时没返回这个字段
                    //播种日期
                    it.startTime.let {
                        mBind.fieldDetailBzTime.text =
                            "${resources.getString(R.string.field_bz_time_tips)}${it}"
                    }
                    //地块位置
                    it.address.let {
                        mBind.fieldDetailAddress.text =
                            "${resources.getString(R.string.field_dk_address_tips)}${it}"
                    }
                    //展示出地块信息
                    mBind.fieldDetailMessage.visibility = View.VISIBLE
                    //设置地块详情信息 ----end----
                    val center02 = it.center02
                    //地图相关展示 ----start----
                    try {
                        val gpsList = JsonUtlis.toTwoArrayList(it.borderCoordinate)
                        val builder = LatLngBounds.builder()
                        val latLngList: MutableList<LatLng> = ArrayList()
                        for (j in gpsList.indices) {
                            val lon = gpsList[j][0]
                            val lat1 = gpsList[j][1]
                            val latLng = LatLng(lat1, lon)
                            latLngList.add(latLng)
                            builder.include(latLng)
                        }
                        latLngList.add(LatLng(gpsList[0][1], gpsList[0][0]))
                        val polygonOpt =
                            PolygonOptions().fillColor(0x4D3E9BFD).strokeColor(-0xbf6302)
                                .strokeWidth(10f)
                        polygonOpt.zIndex(2f)
                        if (fieldPolygon != null) {
                            fieldPolygon?.remove()
                        }
                        fieldPolygon = aMap!!.addPolygon(polygonOpt)
                        fieldPolygon?.points = latLngList
                        val lng = it.centerCoordinate.split(",")[0].toDouble()
                        val lat = it.centerCoordinate.split(",")[1].toDouble()
                        val latLng = LatLng(lat, lng)
                        maker = MarkerOptions().position(latLng)
                            .icon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.field_navigation_img))
                        aMap!!.addMarker(maker)
                        val bounds = builder.build()
                        aMap!!.moveCamera(
                            CameraUpdateFactory.newLatLngBoundsRect(
                                bounds,
                                200,
                                200,
                                400,
                                300
                            )
                        )
                        aMap!!.setOnMarkerClickListener {
                            val openAddressPop = OpenAddressPop(requireContext())
                            XPopup.Builder(requireContext()).setPopupCallback(object :SimpleCallback() {
                                override fun onCreated(popupView: BasePopupView?) {
                                    super.onCreated(popupView)
                                    openAddressPop.setLonandlat(center02)
                                }
                            }).asCustom(openAddressPop).show()
                            false
                        }
                    } catch (e: Exception) {
                        LogUtil.e("加载地块详情地图抛出异常：${e}")
                    }
                    //地图相关展示 ----end----

                    //经纬度转地址 ----start----
                    val longitude = center02.substring(0, center02.indexOf(","))
                    val latitude = center02.substring(center02.indexOf(",") + 1)
                    val geocodeSearch = GeocodeSearch(requireContext())
                    geocodeSearch.setOnGeocodeSearchListener(object :
                        GeocodeSearch.OnGeocodeSearchListener {
                        override fun onRegeocodeSearched(result: RegeocodeResult?, i: Int) {
                            if (result?.regeocodeAddress != null && result.regeocodeAddress.formatAddress != null) {
                                areaId = result.regeocodeAddress.adCode //地区编码
                            }
                        }

                        override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                        }

                    })
                    // 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                    val latLonPoint = LatLonPoint(
                        java.lang.Double.valueOf(latitude),
                        java.lang.Double.valueOf(longitude)
                    )
                    val query = RegeocodeQuery(latLonPoint, 200f, GeocodeSearch.AMAP)
                    geocodeSearch.getFromLocationAsyn(query)
                    //经纬度转地址 ----end----

                }
            })

        /**
         * 天气相关
         */
        viewModel?.fieldWeather?.observe(this, object : BaseStateObserver<FieldWeatherBean>(null) {
            override fun getRespDataSuccess(it: FieldWeatherBean) {
                super.getRespDataSuccess(it)
                //温度
                it.temp.let { mBind.fieldWdValue.text = "${it}℃" }
                //湿度
                it.humidity.let { mBind.fieldSdValue.text = "${it}%" }
                //风力
                it.windlevel.let {
                    mBind.fieldFlValue.text = "${it}${resources.getString(R.string.filed_ji)}"
                }
                //降水
                it.qpf.let { mBind.fieldJsValue.text = "${it}mm" }
            }
        })
        /**
         * 天气相关-积温、积雨
         */
        viewModel?.fieldJfJy?.observe(this, object : BaseStateObserver<FieldJfJy>(null) {
            override fun getRespDataSuccess(it: FieldJfJy) {
                super.getRespDataSuccess(it)
                //积温
                it.temp.let { mBind.fieldJwValue.text = "${it}℃" }
                //积雨
                it.qpf.let { mBind.fieldJyValue.text = "${it}mm" }
            }
        })

    }

    /**
     * 初始化地图相关
     */
    private fun initMapView(savedInstanceState: Bundle?) {
        mBind.filedMap.onCreate(savedInstanceState)
        aMap = FieldEnclosureMapUtil.init(
            mBind.filedMap
        ) { location ->
            if (location != null) {
                val latitude: Double = location.latitude
                val longitude: Double = location.longitude
                curLatLng = LatLng(
                    LocationEnclosureUtil.GCJ2WGSLat(latitude, longitude),
                    LocationEnclosureUtil.GCJ2WGSLon(latitude, longitude)
                )

                if (currLocationMarker == null) {
                    currLocationMarker = aMap?.addMarker(
                        MarkerOptions().position(curLatLng)
                            .icon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.arrows_img))
                            .anchor(0.5f, 0.5f)
                    )
                } else {
                    currLocationMarker?.position = curLatLng
                }
                aMap?.animateCamera(CameraUpdateFactory.newLatLng(curLatLng))

            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == FieldListActivity.REQUEST_CODE && resultCode == FieldListActivity.RESPONSE_CODE){
            val record = data?.getSerializableExtra("data") as Record
            //如果选择的地块跟当前地块不同，就刷新数据
            if(currFieldId != record.fieldId){
                //请求新的地块信息
                mBind.fieldName.text = record.fieldName
                viewModel?.requestFieldDetail(record.fieldId)
            }
        }else if(requestCode == FieldEditorActivity.REQUEST_CODE && resultCode == FieldEditorActivity.RESPONSE_CODE){
            //请求地块信息
            viewModel?.requestField()
        }
    }

    override fun onResume() {
        super.onResume()
        mBind.filedMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBind.filedMap.onResume()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mBind.filedMap.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mBind.filedMap.onDestroy()
        FieldEnclosureMapUtil.destory()
    }


}